<template>
  <el-select
    v-model="valueTitle"
    :disabled="disabled"
    :clearable="clearable"
    multiple
    @clear="clearHandle"
    @remove-tag='removeTag'
  >
    <el-input
      class="serarchInput"
      v-model="serarchValue"
      placeholder="请输入关键字"
    ></el-input>
    <el-option value="" label="">
      <el-tree
        id="tree-option"
        ref="selectTree"
        :accordion="accordion"
        :data="data"
        :props="props"
        show-checkbox
        :node-key="props.value"
        default-expand-all
        :default-checked-keys='valueId'
        @check-change="handleCheckChange"
        @check="handleCheck"
        :filter-node-method="filterNode"
      >
      </el-tree>
    </el-option>
  </el-select>
</template>
<script>
export default {
  name: "ebs-tree-select",
  props: {
    /* 配置项 */
    props: {
      type: Object,
      default: () => {
        return {
          value: "id", // ID字段名
          label: "title", // 显示名称
          children: "children", // 子级字段名
        };
      },
    },
    /* 选项列表数据(树形结构的对象数组) */
    options: {
      type: Array,
      default: () => {
        return [];
      },
    },
    /* 初始值 */
    value: {
      type: Array,
      default: () => {
        return [];
      },
    },
    /* 可清空选项 */
    clearable: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    /* 自动收起 */
    accordion: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    disabled: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
  },
  data() {
    return {
      valueId: this.value, // 初始值
      valueTitle: [],
      checkedData: [],
      serarchValue: '',
      data: this.options
    };
  },
  mounted() {
    this.initHandle();
  },
  methods: {
    filterNode(value, data, node) {
      if (!value) return true;
      let _array = [];//这里使用数组存储 只是为了存储值。
      this.getReturnNode(node,_array,value);
      let result = false;
      console.log(_array)
      _array.forEach((item)=>{
        result = result || item;
      });
      console.log(result)
      return result
      // return data[this.props.label].indexOf(value) !== -1;
    },
    getReturnNode(node,_array,value){
      console.log(node,value)
      let isPass = node.data &&  node.data[this.props.label] && node.data[this.props.label].indexOf(value) !== -1;
      isPass?_array.push(isPass):'';
      this.index++;
      if(!isPass && node.level!=1 && node.parent){
        this.getReturnNode(node.parent,_array,value);
      }
    },
    // 初始化值
    initHandle() {
      // alert('this.valueId=' + this.valueId)
      let that = this;
      // 这里要延迟执行，否则有BUG
      setTimeout(function () {
        if (that.valueId.length) {
          var valueTitle= []
          that.valueId.forEach((item) => {
            valueTitle.push(that.$refs.selectTree.getNode(item).data[that.props.label])
          })
          that.valueTitle = valueTitle
          that.$refs.selectTree.setCheckedKeys(that.valueId); //默认选中
        } else {
          that.valueTitle = []; // 初始化显示
          that.$refs.selectTree.setCheckedKeys([]); // 默认不选中
        }
      }, 200);
      this.$nextTick(() => {
        let scrollWrap = document.querySelectorAll(
          ".el-scrollbar .el-select-dropdown__wrap"
        )[0];
        let scrollBar = document.querySelectorAll(
          ".el-scrollbar .el-scrollbar__bar"
        );
        scrollWrap.style.cssText =
          "margin: 0px; max-height: none; overflow: hidden;";
        scrollBar.forEach((ele) => (ele.style.width = 0));
      });
    },
    // 切换选项
    handleNodeClick(node) {
      console.log(node)
    },
    handleCheck(data, node) {
      // console.log(data,node)
      this.checkedData = node.checkedNodes.filter((item) => {
        return (!item[this.props.children]||!item[this.props.children].length)
      })
      var valueTitle = []
      var valueId = []
      this.checkedData.forEach((item) => {
        valueTitle.push(item[this.props.label])
        valueId.push(item[this.props.value])
      })
      this.valueTitle = valueTitle
      this.valueId = valueId
      this.$emit("input", this.valueId);
      this.$emit("change", this.valueId);
    },
    // 选择处理
    handleCheckChange(data, checked, indeterminate) {
    },
    removeTag(data) {
      this.checkedData = this.$refs.selectTree.getCheckedNodes().filter((item) => {
        return (!item[this.props.children]||!item[this.props.children].length)
      })
      var value = this.checkedData.find((item) => {
        return item[this.props.label] == data
      })
      var valueIndex = this.valueId.findIndex((item) => {
        return value[this.props.value] == item
      })
      this.valueId.splice(valueIndex, 1)
      this.$refs.selectTree.setCheckedKeys(this.valueId)
      this.$emit("input", this.valueId);
      this.$emit("change", this.valueId);
    },
    // 清除选中
    clearHandle() {
      this.valueTitle = [];
      this.valueId = [];
      this.checkedData= []
      this.clearSelected();
      this.$emit("change", []);
    },
    /* 清空选中样式 */
    clearSelected() {
      let allNode = document.querySelectorAll("#tree-option .el-tree-node");
      allNode.forEach((element) => element.classList.remove("is-current"));
    },
  },
  watch: {
    value() {
      this.valueId = this.value;
      this.initHandle();
    },
    serarchValue(val) {
      this.$refs.selectTree.filter(val);
    }
  },
};
</script>
<style scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 274px;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
}
.el-select-dropdown__item.selected {
  font-weight: normal;
}
ul li >>> .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}
.el-tree-node__label {
  font-weight: normal;
}
.el-tree >>> .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree >>> .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}

.el-theme1 .el-select-dropdown.is-multiple .el-select-dropdown__item.selected::after{
  content: '';
}
.serarchInput{
  padding: 10px 20px;
}
</style>
